package com.xiongtian.springframework.beans.factory.support;

import com.xiongtian.springframework.beans.BeansException;
import com.xiongtian.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author: xiongtian
 * @CreateTime: 2025-03-26  09:52
 * @Version: 1.0
 * @Description: JDK实例化策略
 */

public class SimpleInstantiationStrategy implements InstantiationStrategy {

    /**
     * 实例化Bean
     *
     * @param beanDefinition Bean定义
     * @param beanName       Bean名称
     * @param ctor    拿到符合入参信息相对应的构造函数
     * @param args           构造函数入参
     * @return
     */
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        Class clazz = beanDefinition.getBeanClass();
        try {
            if (null != ctor) {
                return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            } else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }
    }
}
